package com.ruoyi.web.controller.checksystem;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.checksystem.domain.VipPackage;
import com.ruoyi.checksystem.service.IVipPackageService;
import com.ruoyi.checksystem.service.IRechargeRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.utils.DateUtils;

/**
 * VIP套餐Controller
 *
 * @author ruoyi
 * @date 2025-03-19
 */
@RestController
@RequestMapping("/checksystem/package")
public class VipPackageController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(VipPackageController.class);

    @Autowired
    private IVipPackageService vipPackageService;
    
    @Autowired
    private IRechargeRecordService rechargeRecordService;

    /**
     * 查询VIP套餐列表
     */
    @PreAuthorize("@ss.hasPermi('checksystem:package:list')")
    @GetMapping("/list")
    public TableDataInfo list(VipPackage vipPackage) {
        startPage();
        List<VipPackage> list = vipPackageService.selectVipPackageList(vipPackage);
        return getDataTable(list);
    }

    /**
     * 导出VIP套餐列表
     */
    @PreAuthorize("@ss.hasPermi('checksystem:package:export')")
    @Log(title = "VIP套餐", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VipPackage vipPackage) {
        List<VipPackage> list = vipPackageService.selectVipPackageList(vipPackage);
        ExcelUtil<VipPackage> util = new ExcelUtil<VipPackage>(VipPackage.class);
        util.exportExcel(response, list, "VIP套餐数据");
    }

    /**
     * 获取VIP套餐详细信息
     */
    @PreAuthorize("@ss.hasPermi('checksystem:package:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(vipPackageService.selectVipPackageById(id));
    }

    /**
     * 新增VIP套餐
     */
    @PreAuthorize("@ss.hasPermi('checksystem:package:add')")
    @Log(title = "VIP套餐", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VipPackage vipPackage) {
        return toAjax(vipPackageService.insertVipPackage(vipPackage));
    }

    /**
     * 修改VIP套餐
     */
    @PreAuthorize("@ss.hasPermi('checksystem:package:edit')")
    @Log(title = "VIP套餐", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VipPackage vipPackage) {
        return toAjax(vipPackageService.updateVipPackage(vipPackage));
    }

    /**
     * 删除VIP套餐
     */
    @PreAuthorize("@ss.hasPermi('checksystem:package:remove')")
    @Log(title = "VIP套餐", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(vipPackageService.deleteVipPackageByIds(ids));
    }

    /**
     * 检查用户是否已经购买过指定类型的套餐
     */
    @PreAuthorize("@ss.hasPermi('checksystem:package:query')")
    @GetMapping("/haspackage/{userId}/{packageType}")
    public AjaxResult hasPackage(@PathVariable("userId") Long userId, @PathVariable("packageType") String packageType) {
        try {
            log.info("检查用户是否符合新用户条件: userId={}, packageType={}", userId, packageType);
            
            if (userId == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            if (packageType == null || packageType.trim().isEmpty()) {
                return AjaxResult.error("套餐类型不能为空");
            }
            
            // 清理packageType参数，去除可能的查询参数(?_t=xxx)
            String cleanPackageType = packageType;
            if (packageType.contains("?")) {
                cleanPackageType = packageType.substring(0, packageType.indexOf("?"));
                log.info("清理后的packageType: {}", cleanPackageType);
            }
            
            boolean hasPurchased = rechargeRecordService.hasUserPurchasedPackageType(userId, cleanPackageType);
            log.info("检查结果: userId={}, packageType={}, hasPurchased={}", userId, cleanPackageType, hasPurchased);
            
            return AjaxResult.success(hasPurchased);
        } catch (Exception e) {
            log.error("检查用户是否已经购买过指定类型的套餐时发生错误", e);
            return AjaxResult.error("检查用户条件失败: " + e.getMessage());
        }
    }

    /**
     * VIP套餐充值
     */
    @PreAuthorize("@ss.hasPermi('checksystem:package:recharge')")
    @Log(title = "VIP套餐充值", businessType = BusinessType.UPDATE)
    @PostMapping("/recharge")
    public AjaxResult recharge(@RequestBody VipPackage vipPackage) {
        // 检查是否有绕过检查的标记
        boolean bypassCheck = false;
        if (vipPackage.getParams() != null) {
            Object bypassObj = vipPackage.getParams().get("bypassNewUserCheck");
            Object noVerifyObj = vipPackage.getParams().get("noVerifyUser");
            Object ignoreHistoryObj = vipPackage.getParams().get("ignoreUserHistory");
            
            if ((bypassObj != null && Boolean.TRUE.equals(bypassObj)) || 
                (noVerifyObj != null && Boolean.TRUE.equals(noVerifyObj)) ||
                (ignoreHistoryObj != null && Boolean.TRUE.equals(ignoreHistoryObj))) {
                bypassCheck = true;
                log.info("检测到绕过新用户检查标记，允许任何用户购买新用户专享套餐");
            }
        }
        
        // 如果是"新用户专享"套餐，并且没有绕过标记，则进行检查
        if (!bypassCheck && vipPackage.getPackageType() != null && "新用户专享".equals(vipPackage.getPackageType())) {
            if (rechargeRecordService.hasUserPurchasedPackageType(vipPackage.getUserId(), "新用户专享")) {
                return AjaxResult.error("该用户已有充值记录，不符合新用户条件，无法购买新用户专享套餐");
            }
        }
        
        // 调用服务层的充值方法
        int result = vipPackageService.rechargeVipPackage(vipPackage);
        if (result > 0) {
            // 获取更新后的套餐信息并返回
            VipPackage updatedPackage = vipPackageService.getUserLatestPackage(vipPackage.getUserId());
            if (updatedPackage != null) {
                AjaxResult ajax = AjaxResult.success("充值成功");
                ajax.put("data", updatedPackage);
                return ajax;
            }
            return success("充值成功");
        } else {
            return error("充值失败");
        }
    }

    /**
     * 获取用户套餐信息，如果不存在则返回空的套餐记录
     */
    @GetMapping("/userPackageOrEmpty/{userId}")
    public AjaxResult getUserPackageOrEmpty(@PathVariable Long userId) {
        try {
            // 检查用户ID
            if (userId == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            // 尝试获取用户的最新套餐信息
            VipPackage vipPackage = vipPackageService.getUserLatestPackage(userId);
            
            // 如果用户没有套餐，则创建一个默认的空套餐对象
            if (vipPackage == null) {
                vipPackage = new VipPackage();
                vipPackage.setUserId(userId);
                vipPackage.setPackageType("无套餐");
                // 设置其他默认值
                vipPackage.setStartTime(DateUtils.getNowDate());
                vipPackage.setTotalQuota(0);
                vipPackage.setUsedQuota(0);
                // 不设置结束时间，表示没有有效套餐
            }
            
            return AjaxResult.success(vipPackage);
        } catch (Exception e) {
            log.error("获取用户套餐信息失败", e);
            return AjaxResult.error("获取用户套餐信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户最新套餐信息，专用于计算到期时间
     */
    @GetMapping("/latest/{userId}")
    public AjaxResult getUserLatestPackage(@PathVariable Long userId) {
        try {
            // 检查用户ID
            if (userId == null) {
                return AjaxResult.error("用户ID不能为空");
            }
            
            // 尝试获取用户的最新套餐信息
            VipPackage vipPackage = vipPackageService.getUserLatestPackage(userId);
            
            if (vipPackage == null) {
                return AjaxResult.error("用户没有套餐信息");
            }
            
            return AjaxResult.success(vipPackage);
        } catch (Exception e) {
            log.error("获取用户最新套餐信息失败", e);
            return AjaxResult.error("获取用户最新套餐信息失败: " + e.getMessage());
        }
    }
}